#include "LEDStrip.h"

#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/spi/spidev.h>

#define Device "/dev/spidev0.0"

static int fd;

void InitializeLEDStrip()
{
	fd=open(Device,O_RDWR);
	if(fd<0)
	{
		fprintf(stderr,"Error opening %s\n",Device);
		exit(1);
	}

	int mode=SPI_MODE_0;
	if(ioctl(fd,SPI_IOC_WR_MODE,&mode)<0) { fprintf(stderr,"Error configuring %s\n",Device); exit(1); }
	if(ioctl(fd,SPI_IOC_RD_MODE,&mode)<0) { fprintf(stderr,"Error configuring %s\n",Device); exit(1); }
}

void UpdateLEDStripWithClockRate(uint32_t strip[240],int clock)
{
	uint8_t output[3*240+3];
	uint8_t input[3*240+3];

	for(int i=0;i<240;i++)
	{
		uint8_t r=strip[i];
		uint8_t g=strip[i]>>8;
		uint8_t b=strip[i]>>16;

		output[3*i+0]=0x80|b;
		output[3*i+1]=0x80|r;
		output[3*i+2]=0x80|g;
	}

	output[3*240+0]=0;
	output[3*240+1]=0;
	output[3*240+2]=0;

    ioctl(fd,SPI_IOC_MESSAGE(1),&(struct spi_ioc_transfer){
		.tx_buf=(unsigned long)output,
		.rx_buf=(unsigned long)input,
		.len=3*240+3,
		.delay_usecs=0,
		.speed_hz=clock,
		.bits_per_word=8,
	});
}

